<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="onSearch"
        />
        <el-tree
          ref="tree"
          node-key="id"
          default-expand-all
          :data="list"
          :props="defaultProps"
          :expand-on-click-node="false"
          highlight-current

          @current-change="nodeChange"
        />
        <!-- 树形组件 -->
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="addemployee">添加员工</el-button>
          <!--父传子方法1. 点击excel导入 弹层显示 -->
          <el-button size="mini" @click="visible=true">excel导入</el-button>
          <el-button size="mini" @click="onExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="editEmployee(row.id)">查看</el-button>
              <el-button size="mini" type="text" @click="showDialog(row.id)">角色</el-button>
              <el-popconfirm title="这是一段内容确定删除吗?" @onConfirm="delEmployee(row.id)">

                <el-button slot="reference" size="mini" type="text" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :page-size="pageParams.pagesize"
            :current-page="pageParams.page"
            :total="pageParams.total"
            @current-change="changePage"
          />
        </el-row>
      </div>

    </div>
    <!-- 分配角色弹层 -->
    <el-dialog title="分配角色" :visible.sync="roleVisible" width="500px">
      <el-checkbox-group v-model="allotEmployeeIdList">
        <!-- 多选框 -->
        <el-checkbox v-for="item in enableEmployeeList" :key="item.id" :label="item.id">{{
          item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="onAllotRole">确定</el-button>
          <el-button size="mini" @click="roleVisible=false">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
    <!--父传子方法3. 为弹层绑定visible属性显示（父传子 传visible到子组件） -->
    <add-import :visible.sync="visible" />
  </div>
</template>

<script>
import fileSaver from 'file-saver'
import { getDepartmentAPI } from '@/api/department'
import { allotRoleAPI, delEmployeeAPI, enableEmployeeListAPI, exportEmployeeListAPI, getEmployeeListAPI, getEmployeeParticularsAPI } from '@/api/employee'
import { list2Tree } from '@/utils'
import addImport from './components/add-import.vue'
export default {
  name: 'Employee',
  components: { addImport },
  data() {
    return {
      // 分配角色id列表
      allotEmployeeIdList: [],
      // 已启用的角色列表
      enableEmployeeList: [],
      // 角色弹层
      roleVisible: false,
      // 父传子方法 2.定义控制excel导入弹层显示
      visible: false,
      // 模糊搜索框参数
      keyword: '',
      // 员工列表
      employeeList: [],
      // 部门列表
      list: [],
      // tree数组件绑定的属性
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      pageParams: {
        // 第几页
        page: 1,
        // 一页多少个数据
        pagesize: 10,
        // 总数量
        total: 0
      },
      // 定义一个部门ID
      departmentId: null
    }
  },
  // 最先发请求
  async created() {
    const res = await getDepartmentAPI()
    this.list = list2Tree(res, 0)
    // 将传智教育根节点的ID赋值给部门ID
    this.departmentId = this.list[0].id
    // 调用获取员工列表方法
    this.getEmployeeList()
    // 设置选中默认节点
    this.$nextTick(() => {
      this.$refs.tree.setCurrentKey(this.list[0].id)
    })
  },
  methods: {
    // 角色按钮
    async  showDialog(id) {
      // 可以用this.id=id定义出来变量（前提是这个id不需要显示用来画面）
      this.id = id
      this.enableEmployeeList = await enableEmployeeListAPI()
      const { roleIds } = await getEmployeeParticularsAPI(id)
      this.allotEmployeeIdList = roleIds
      this.roleVisible = true
    },
    // 分配角色弹层确定按钮
    async onAllotRole() {
      await allotRoleAPI({ id: this.id, roleIds: this.allotEmployeeIdList })
      this.roleVisible = false
      this.$message.success('分配角色成功')
    },
    // 封装获取员工列表方法
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListAPI({ departmentId: this.departmentId, keyword: this.keyword })
      this.employeeList = rows
      this.pageParams.total = total
    },
    // 节点发生改变根据ID 重新发请求 获取部门员工
    nodeChange(node) {
      this.departmentId = node.id
      this.getEmployeeList()
    },
    // 分页改变 发请求更新数据
    async changePage(paging) {
      this.pageParams.page = paging
      const { rows, total } = await getEmployeeListAPI({ ...this.pageParams, departmentId: this.departmentId })
      this.employeeList = rows
      this.pageParams.total = total
    },
    // 添加员工按钮
    addemployee() {
      this.$router.push('/addemployee')
    },
    // 查看编辑员工按钮
    editEmployee(id) {
      this.$router.push({ path: '/addemployee', query: { id }})
    },
    // 员工模糊搜索
    onSearch() {
      clearTimeout(this.timerId)
      this.timerId = setTimeout(() => {
        this.getEmployeeList()
      }, 1000)
    },
    // 导出按钮
    async onExport() {
      const res = await exportEmployeeListAPI()
      fileSaver.saveAs(res, 'xlsx')
    },
    // 删除按钮
    async delEmployee(id) {
      await delEmployeeAPI(id)
      this.employeeList.length === 1 && this.pageParams.page--
      this.getEmployeeList()
      this.$message.success('删除成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
